package com.oi.test01.hw.tiMu11;

import com.oi.test01.entity.Demo1;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;

/**
 * @author bin
 * @date 2025 - 03 -19
 **/
public class BeanUtil {

    //设置属性
    public static void setProperty(Object bean, String propertyName, Object value) throws Exception {
        System.out.println("进来时的值"+bean);
        Class<?> aClass = bean.getClass();
        Constructor<?> constructor = aClass.getConstructor();
        Object o = constructor.newInstance();
        Field field = aClass.getDeclaredField(propertyName);
        field.setAccessible(true);
        field.set(o, value);
        System.out.println(o);
    }
    //获取对象值
    public static Object getProperty(Object bean, String propertyName) throws Exception {
        Class<?> aClass = bean.getClass();
        Field field = aClass.getDeclaredField(propertyName);
        field.setAccessible(true);
        return field.get(bean);
    }

    // 3、复制某个对象的属性值到另一个对象中
    public static void copyProperties(Object source, Object target) throws Exception {
        System.out.println("进来时的值"+source);
        System.out.println("进来时的值"+target);
        Class<?> class1 = source.getClass();
        Class<?> class2 = target.getClass();
        Field[] Fields = class1.getDeclaredFields();
        for (Field field : Fields) {
            field.setAccessible(true);
            field.set(target, field.get(source));
        }
        System.out.println("完成时的值"+source);
        System.out.println("完成时的值"+target);
    }
    public static void main(String[] args) throws Exception {
//        setProperty(new Demo1(), "name", "bin");

//        System.out.println(getProperty(new Demo1("张三", 18, "男"), "name"));

        Demo1 d1 = new Demo1("张三", 18, "男");
        Demo1 d2 = new Demo1();
        copyProperties(d1,d2);
    }
}
